package cn.weiwei.WHadoop.Avro;


import cn.weiwei.WHadoop.Avro.domain.StringPair;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * <pre>序列化与反序列化 StringPair 工具类</pre>
 * @author Wang Weiwei <email>weiwei02@vip.qq.com / weiwei.wang@100credit.com</email>
 * @version 1.0
 * @sine 2017/4/12
 */
public class SerializeStringPair {
    public StringPair stringPair;

    public SerializeStringPair(){
        stringPair = new StringPair();
        stringPair.setLeft("L");
        stringPair.setRight("R");
    }

    /**序列化*/
    public byte[] serialize() throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        DatumWriter<StringPair> stringPairDatumWriter = new SpecificDatumWriter<StringPair>(StringPair.class);
        Encoder encoder = EncoderFactory.get().binaryEncoder(stream,null);
        stringPairDatumWriter.write(stringPair,encoder);
        encoder.flush();
        stream.close();
        return stream.toByteArray();
    }

    /**
     * 反序列化
     * */
    public void deSerialize(byte[] data) throws IOException {
        DatumReader<StringPair> stringPairDatumReader = new SpecificDatumReader<StringPair>(StringPair.class);
        Decoder decoder = DecoderFactory.get().binaryDecoder(data,null);
        StringPair stringPair = stringPairDatumReader.read(null,decoder);
        System.out.println(stringPair);
    }


}
